package com.gyt.manager.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 日期时间工具类
 * @author wenhsh
 *
 */
public class DateTimeUtility {
	private static Logger LOGGER = LoggerFactory.getLogger(DateTimeUtility.class);

	private static final long ONE_MINUTE = 60000L;
	private static final long ONE_HOUR = 3600000L;
	private static final long ONE_DAY = 86400000L;
	private static final long ONE_WEEK = 604800000L;
	
	private static final String ONE_SECOND_AGO = "刚刚";
	private static final String ONE_MINUTE_AGO = "分钟前";
	private static final String ONE_HOUR_AGO = "小时前";
	private static final String ONE_DAY_AGO = "天前";
	private static final String ONE_MONTH_AGO = "月前";
	private static final String ONE_YEAR_AGO = "年前";

	public static final String PATTERN_DATE_TIME = "yyyy-MM-dd HH:mm:ss";

	private static final ThreadLocal<DateFormat> SDF_YMDHMS = new ThreadLocal<DateFormat>() {
		@Override
		protected DateFormat initialValue() {
			return new SimpleDateFormat("yyyyMMddHHmmss");
		}
	};
	private static final ThreadLocal<DateFormat> SDF_YMDHMS_MS = new ThreadLocal<DateFormat>() {
		@Override
		protected DateFormat initialValue() {
			return new SimpleDateFormat("yyyyMMddHHmmssSSS");
		}
	};

	/**
	 * @param dateStr yyyyMMddHHmmss或者yyyyMMddHHmmss格式
	 * @return
	 */
	public static Date parseYmdHmsContinue(String dateStr) {
		if (StringUtils.isBlank(dateStr)) {
			return null;
		}
		try {
			int len = 14;
			if (dateStr.length() <= len) {
				return SDF_YMDHMS.get().parse(dateStr);
			} else {
				return SDF_YMDHMS_MS.get().parse(dateStr);
			}

		} catch (Exception e) {
			LOGGER.error("failed parse date string InYMD.dateStr:" + dateStr, e);
		}
		return null;
	}
	
	public static String relativeDateFormat(Date date) {
		long delta = new Date().getTime() - date.getTime();
		if (delta < 1L * ONE_MINUTE) {
//			long seconds = toSeconds(delta);
//			return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;
			return ONE_SECOND_AGO;
		}
		if (delta < 45L * ONE_MINUTE) {
			long minutes = toMinutes(delta);
			return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;
		}
		if (delta < 24L * ONE_HOUR) {
			long hours = toHours(delta);
			return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;
		}
		if (delta < 48L * ONE_HOUR) {
			return "昨天";
		}
		if (delta < 30L * ONE_DAY) {
			long days = toDays(delta);
			return (days <= 0 ? 1 : days) + ONE_DAY_AGO;
		}
		if (delta < 12L * 4L * ONE_WEEK) {
			long months = toMonths(delta);
			return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;
		} else {
			long years = toYears(delta);
			return (years <= 0 ? 1 : years) + ONE_YEAR_AGO;
		}
	}

	private static long toSeconds(long date) {
		return date / 1000L;
	}

	private static long toMinutes(long date) {
		return toSeconds(date) / 60L;
	}

	private static long toHours(long date) {
		return toMinutes(date) / 60L;
	}

	private static long toDays(long date) {
		return toHours(date) / 24L;
	}

	private static long toMonths(long date) {
		return toDays(date) / 30L;
	}

	private static long toYears(long date) {
		return toMonths(date) / 365L;
	}
    
    /**
     * 返回当前日期
     */
    public static String dateofnow() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }

    /**
     * 返回当前日期
     * 当前时间未超过04:00 返回前一天的日期
     */
    public static String dateofnow2() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = sdf.format(new Date());
        int strDateH = Integer.parseInt(strDate.substring(11, 13));
        if(0 < strDateH && strDateH <= 3) {
            // 当前时间未超过04:00 返回前一天的日期
            return addDate(null,"D", -1);
        } else {
            return dateofnow();
        }
    }

	/**
	 * 返回当前日期格式为20070921
	 */
	public static String dateofnowonlynumber() {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(new Date());
	}

	/**
	 * 返回当前日期格式为20070921
	 */
	public static String dateToday(Date date) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(date);
	}

	/**
	 * 返回当前时间
	 */
	public static String timeofnow() {
		return timeofnow("yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 返回当前时间
	 */
	public static String timeofnow(String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		Calendar curcal = Calendar.getInstance();
		return sdf.format(curcal.getTime());
	}

	public static String timeofnow(Date date, String pattern) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date.getTime());
	}

	/**
	 * 返回指定格式时间
	 */
	public static String timeofnow(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (date == null)
			return "";
		return sdf.format(date);
	}
	
	/**
	 * 返回指定格式时间
	 */
	public static String dateofnow(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (date == null)
			return "";
		return sdf.format(date);
	}
	
	/**
	 * 返回昨天的日期
	 */
	public static String dateofyesterday() {
		Calendar cal=Calendar.getInstance();
		cal.add(Calendar.DATE,-1);
		String yesterday = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
		return yesterday;
	}
	
	/**
	 * beforeDate - afterDate
	 * @param beforeDate
	 * @param afterDate
	 * @return
	 */
	public static int getIntervalDays(Date beforeDate, Date afterDate) {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(beforeDate);
		calendar2.setTime(afterDate);
		int year1 = calendar1.get(Calendar.YEAR);
		int year2 = calendar2.get(Calendar.YEAR);
		int day1 = calendar1.get(Calendar.DAY_OF_YEAR);
		int day2 = calendar2.get(Calendar.DAY_OF_YEAR);
		return (year1 - year2) * 365 + day1 - day2;
	}
	
	/**
	 * beforeDate - afterDate 两个日期相差多少分钟（一般比较同一天内的）
	 * @param beforeDate
	 * @param afterDate
	 * @return
	 */
	public static int getIntervalMinutes(Date beforeDate, Date afterDate) {
		    long nm = 1000 * 60;
		    // long ns = 1000;
		    // 获得两个时间的毫秒时间差异
		    long diff = beforeDate.getTime() - afterDate.getTime();
		    // 计算差多少分钟
		    long min = diff / nm;
		return (int) Math.abs(Math.ceil(Double.valueOf(min)));
	}

	
	/**
	 * 返回指定格式时间
	 */
	public static String timeofnowFormat(Date date,String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if (date == null)
			return "";
		return sdf.format(date);
	}

	public static String timeofnowFromStr(String dateStr){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(dateStr == null){
			return "";
		}
		try {
			return timeofnow(sdf.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String dateofnowFromStr(String dateStr){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(dateStr == null){
			return "";
		}
		try {
			return dateofnow(sdf.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 生成固定长度的序列号，不足位数在前补0
	 */
	public static String createSerial(String src, int len) {
		String dest = "";
		if (src.length() >= len) {
			dest = src.substring(0, len);
		} else {
			dest = createSameChar("0", len - src.length()) + src;
		}
		return dest;
	}

	/**
	 * 返回一样字符的串
	 */
	public static String createSameChar(String src, int len) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < len; i++) {
			sb.append(src);
		}
		return sb.toString();
	}

	/**
	 * 得到系统的时间戳
	 */
	public static long getTradeSn() {
		return new Date().getTime();
	}

	/**
	 * 得到指定时间的时间戳
	 */
	public static long getTransTime(String transTime){
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d = sdf.parse(transTime);
			return d.getTime();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static Date stringToDate(String time) {
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d = sdf.parse(time);
			return d;
			
		}catch(Exception e){
			return null;
		}
	}

	/**
	 * 拷贝属性 主要是为了封装 org.apache.commons.beanutils.BeanUtils.copyProperties 的异常
	 */
	public static void copyProperties(Object dest, Object src) {
		try {
			org.apache.commons.beanutils.BeanUtils.copyProperties(dest, src);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对迅雷ID进行计算，范围00-99 flag = 0 : 根据1-2位计算库 flag = 1 : 根据3-4位计算表 dbflag = 0 :
	 * 根据1-2位计算库，范围00-99 dbflag = 1 : 根据1-2位计算库，范围00-09
	 */
	/*
	 * public static String getXunleiIdHash(String xunleiid, int flag, int
	 * dbflag) throws Exception{ String src = null, rtn = null; String xunleiid2
	 * = xunleiid.toLowerCase(); int sum = 0; int mod = 0; if(flag == 0) src =
	 * xunleiid2.substring(0, 2); else if(flag == 1) src =
	 * xunleiid2.substring(2, 4); else throw new
	 * Exception("getXunleiIdHash error"); //System.out.println("src=" + src);
	 * 
	 * byte[] bytesrc = src.getBytes(); for(int i = 0; i < bytesrc.length; i
	 * ++){ //System.out.println(bytesrc[i]); sum += bytesrc[i]; } mod = sum %
	 * 100; if(flag == 0 && dbflag == 1) mod = mod % 10;
	 * //System.out.println("sum=" + sum + ", mod=" + mod); if(mod < 10) rtn =
	 * "0" + mod; else rtn = "" + mod; return rtn; }
	 */

	/**
	 * 对迅雷ID进行计算，范围00-99 flag = 0 : 根据1-2位计算库 flag = 1 : 根据3-4位计算表 dbflag = 0 :
	 * 根据1-2位计算库，范围00-99 dbflag = 1 : 根据1-2位计算库，范围00-09
	 */
	public static String getXunleiIdHash(String xunleiid, int flag, int dbflag)
			throws Exception {
		String rtn = null;
		if (xunleiid.length() != 14)
			throw new Exception("getXunleiIdHash error xunleiid=" + xunleiid);
		if (isNumber(xunleiid) == false)
			throw new Exception("getXunleiIdHash error xunleiid=" + xunleiid);
		if (flag == 0 && dbflag == 0)
			rtn = xunleiid.substring(0, 2);
		else if (flag == 0 && dbflag == 1)
			rtn = "0" + xunleiid.substring(1, 2);
		else if (flag == 1)
			rtn = xunleiid.substring(2, 4);
		else
			throw new Exception("getXunleiIdHash error");
		return rtn;
	}

	/**
	 * 对迅雷ID(个人中心内部ID)进行计算，范围00-99
	 * 
	 * @param xunleiId
	 * @param flag
	 *            计算库或者是表的标志位。为0时，计算库；为1时，计算表
	 * @param dbflag
	 *            计算库。为0时，则库的范围为00-99；为1时 ，则库的范围00-09
	 * @return 库或者表的数字后缀
	 * @throws Exception
	 */
	public static String getXunleiNumIdHash(String xunleiId, int flag,
			int dbflag) throws Exception {
		String rtn = null;
		Long xunleiid = Long.valueOf(xunleiId);

		if (flag == 0) {
			// 取得代表库的倒数3、4位的数字
			int databasenum = (int) ((xunleiid / 100) % 100);
			if (dbflag == 0) {// 倒数3、4位为表
				rtn = databasenum < 10 ? "0" + databasenum : String
						.valueOf(databasenum);
			} else if (dbflag == 1) {// 倒数第3为为表
				databasenum = databasenum % 10;
				rtn = "0" + databasenum;
			}
		} else if (flag == 1) {// 后两位为表
			int tablenum = (int) (xunleiid % 100);
			rtn = tablenum < 10 ? "0" + tablenum : String.valueOf(tablenum);
		} else {
			throw new Exception("getXunleiNumIdHash error");
		}
		return rtn;
	}

	private final static Pattern pnumber = Pattern.compile("\\d+");

	/**
	 * 是否是数字
	 * 
	 * @param s
	 *            目标字符串
	 * @return 是否是数字
	 */
	public static boolean isNumber(String s) {
		if (isEmpty(s)) {
			return false;
		}
		Matcher m = pnumber.matcher(s);
		return m.matches();
	}

	public static boolean isEmpty(String s) {
		if (null == s || s.trim().equals("")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 取固定长度字符串， 不足补
	 */
	public static String getFixedLengthString(String src, String c, int len) {
		if (src.length() >= len)
			return src.substring(0, len);
		StringBuffer ext = new StringBuffer();
		for (int i = src.length(); i < len; i++) {
			ext.append(c);
		}
		return src + ext.toString();
	}

	/**
	 * 给指定时间加上一个数值
	 * 
	 * @param time1
	 *            要加上一数值的时间，为null即为当前时间，格式为yyyy-MM-dd HH:mm:ss
	 * @param addpart
	 *            要加的部分：年月日时分秒分别为：YMDHFS
	 * @param num
	 *            要加的数值
	 * @return 新时间，格式为yyyy-MM-dd HH:mm:ss
	 */
	public static String addTime(String time1, String addpart, int num) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String now = sdf.format(new Date());
			time1 = (time1 == null) ? now : time1;
			if (time1.length() < 19) {
				time1 += " 00:00:00";
			}
			GregorianCalendar cal = new GregorianCalendar();
			cal.setTime(sdf.parse(time1));
			if (addpart.equalsIgnoreCase("Y")) {
				cal.add(Calendar.YEAR, num);
			} else if (addpart.equalsIgnoreCase("M")) {
				cal.add(Calendar.MONTH, num);
			} else if (addpart.equalsIgnoreCase("D")) {
				cal.add(Calendar.DATE, num);
			} else if (addpart.equalsIgnoreCase("H")) {
				cal.add(Calendar.HOUR, num);
			} else if (addpart.equalsIgnoreCase("F")) {
				cal.add(Calendar.MINUTE, num);
			} else if (addpart.equalsIgnoreCase("S")) {
				cal.add(Calendar.SECOND, num);
			}
			return sdf.format(cal.getTime());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 给指定时间加上一个数值
	 * 
	 * @param time1
	 *            要加上一数值的时间，为null即为当前时间，格式为格式可自定义传入
	 * @param addpart
	 *            要加的部分：年月日时分秒分别为：YMDHFS
	 * @param num
	 *            要加的数值
	 * @return 新时间，格式可自定义传入
	 */
	public static String addTimeFormat(String time1, String addpart, int num, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			String now = sdf.format(new Date());
			time1 = (time1 == null) ? now : time1;
			if (time1.length() < 19) {
				time1 += " 00:00:00";
			}
			GregorianCalendar cal = new GregorianCalendar();
			cal.setTime(sdf.parse(time1));
			if (addpart.equalsIgnoreCase("Y")) {
				cal.add(Calendar.YEAR, num);
			} else if (addpart.equalsIgnoreCase("M")) {
				cal.add(Calendar.MONTH, num);
			} else if (addpart.equalsIgnoreCase("D")) {
				cal.add(Calendar.DATE, num);
			} else if (addpart.equalsIgnoreCase("H")) {
				cal.add(Calendar.HOUR, num);
			} else if (addpart.equalsIgnoreCase("F")) {
				cal.add(Calendar.MINUTE, num);
			} else if (addpart.equalsIgnoreCase("S")) {
				cal.add(Calendar.SECOND, num);
			}
			return sdf.format(cal.getTime());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	

	/**
	 * 给指定日期加上一个数值
	 * 
	 * @param date1
	 *            要加上一数值的日期，为null即为当前日期，格式为yyyy-MM-dd
	 * @param addpart
	 *            要加的部分：年月日分别为：YMD
	 * @param num
	 *            要加的数值
	 * @return 新日期，格式为yyyy-MM-dd
	 */
	public static String addDate(String date1, String addpart, int num) {
		return addTime(date1, addpart, num).substring(0, 10);
	}
	
	public static Date formatTime(String dataStr){
		try{
			SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return simple.parse(dataStr);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static Date formatHHMM(String dataStr){
		try{
			SimpleDateFormat simple = new SimpleDateFormat("HH:mm");
			return simple.parse(dataStr);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static Date formatDate(String dataStr){
		try{
			SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
			return simple.parse(dataStr);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 计算当天当前时间剩余的毫秒数
	 * @return
	 */
	public static long getLeavingTime(){
		 try{
			 long nowoftime = Long.valueOf(getTradeSn());
			 long endoftime = Long.valueOf(getTransTime(dateofnow() + " 23:59:59"));
			 long rtnTime =(endoftime - nowoftime);
			 return rtnTime;
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 return 0;
	}
	
	/**
	 * 计算当天当时时间到本周最后剩余的毫秒数
	 * @return
	 */
	public static long getWeekLeavingTime(){
		try{
			 long nowoftime = Long.valueOf(getTradeSn());
			 long endoftime = Long.valueOf(getTransTime(getLastDayInWeek() + " 23:59:59"));
			 long rtnTime =(endoftime - nowoftime);
			 return rtnTime;
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 return 0;
	}
	/**
	 * 计算当天当时时间到本月最后剩余的毫秒数
	 * @return
	 */
	public static long getMonthLeavingTime(){
		try{
			 long nowoftime = Long.valueOf(getTradeSn());
			 long endoftime = Long.valueOf(getTransTime(getLastDayInMonth() + " 23:59:59"));
			 long rtnTime =(endoftime - nowoftime);
			 return rtnTime;
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 return 0;
	}
	
	/**
	 * 获取当前月份的第一天
	 * @return
	 */
	public static String getFirstDayInMonth(Date date){
		String rtnStr = null;
		try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal_1 = Calendar.getInstance();//获取当前日期
			if(date != null) cal_1.setTime(date);
			cal_1.add(Calendar.MONTH, 0);
			cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
			rtnStr = format.format(cal_1.getTime());
		}catch(Exception e){
		}
		return rtnStr;
	}
	
	/**
	 * 获取当前月份的最后一天
	 * @return
	 */
	public static String getLastDayInMonth(){
		String rtnStr = null;
		try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar ca = Calendar.getInstance();//获取当前日期
			ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));  
			rtnStr = format.format(ca.getTime());
		}catch(Exception e){
		}
		return rtnStr;
	}
	
	/**
	 * 获取当周的最后一天
	 * @return
	 */
	public static String getLastDayInWeek(){
		String rtnStr = null;
		try{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar ca = Calendar.getInstance();//获取当前日期
			ca.set(Calendar.DAY_OF_WEEK, ca.getActualMaximum(Calendar.DAY_OF_WEEK));  
			rtnStr = format.format(ca.getTime());
		}catch(Exception e){
		}
		return rtnStr;
	}
	
	/**
	 * 把数字表示的星期转换为中文的格式，如：周一
	 * @param num 数字型的星期
	 * @return
	 */
	public static String transNum2Week(int num){
		String rtnStr = "--";
		if(num == 1){
			rtnStr = "周一";
		}else if(num == 2){
			rtnStr = "周二";
		}else if(num == 3){
			rtnStr = "周三";
		}else if(num == 4){
			rtnStr = "周四";
		}else if(num == 5){
			rtnStr = "周五";
		}else if(num == 6){
			rtnStr = "周六";
		}else if(num == 7){
			rtnStr = "周日";
		}
		return rtnStr;
	}
	
	/**
	 * 取得当月天数
	 * */
	public static int getCurrentMonthDayCount(){
		Calendar a = Calendar.getInstance();
		a.set(Calendar.DATE, 1);//把日期设置为当月第一天
		a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}
	
	public static String timeofWeiXinPay(String dateStr){
		if(StringUtils.isNotEmpty(dateStr)){
			return dateStr.replaceAll(":", "").replaceAll(" ", "").replaceAll("-", "");
		}else{
			throw new RuntimeException("param [dateStr] can not be null!");
		}
	}
	
	/**
	 * 获取对应的日期是周几（同一到周日）
	 * @param date
	 * @return
	 */
	public static String getDateWeek(Date date){
		String weekDesc = "--";
		int[] weekDays = {7, 1, 2, 3, 4, 5, 6};
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		int weekTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		weekDesc = transNum2Week(weekDays[weekTemp]);
		return weekDesc;
	}
	
	/**
	 * 获取对应的日期是周几（1-7返回）
	 * @param date
	 * @return
	 */
	public static int getDateWeekNum(Date date){
		int[] weekDays = {7, 1, 2, 3, 4, 5, 6};
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		int weekTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		return weekDays[weekTemp];
	}
	
	/**
	 * 根据生日日期获取年龄
	 * @param birthday 生日
	 * @return
	 */
	public static int getAgeByBirth(String birthday) {
        int age = 0;
        if(StringUtils.isEmpty(birthday)){
        	return age;
        }
        Date birthDate = DateTimeUtility.formatDate(birthday);
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthDate);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
           return 0;
        }
    }
	
	/**
	 * 组装成近7天的日期（周一排首位）
	 * @return
	 */
	public static List<Map<String, Object>> generateWeeks(){
		int[] weekDays = {7, 1, 2, 3, 4, 5, 6};
		List<Map<String, Object>> list = new ArrayList<>();
		Calendar calendar = Calendar.getInstance();
		int temp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		int todayWeek = weekDays[temp];
		Date date = new Date();
		
		int beforeIndex = todayWeek - 1;
		int afterIndex = 7 - todayWeek;
		
		if(beforeIndex > 0){
			for(int i = beforeIndex; i >= 1; i--){
				Map<String, Object> tempMap = new HashMap<>();
				calendar.setTime(date);
				calendar.add(Calendar.DATE, -i);
				int weekTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
				String weekDesc = transNum2Week(weekDays[weekTemp]);
				boolean isToday = false;
				tempMap.put("weekDesc", weekDesc);
				if(i == todayWeek){
					isToday = true;
				}
				tempMap.put("isToday", isToday);
				int month = calendar.get(Calendar.MONTH) + 1;
				int day = calendar.get(Calendar.DAY_OF_MONTH);
				String dateValue = DateTimeUtility.dateofnow(calendar.getTime());
				tempMap.put("dateValue", dateValue);
				tempMap.put("today", month + "/" + day);
				list.add(tempMap);
			}
		}
		if(afterIndex > 0){
			for(int j = todayWeek; j <= 7; j++){
				int range = j - todayWeek;
				Map<String, Object> tempMap = new HashMap<>();
				calendar.setTime(date);
				calendar.add(Calendar.DATE, range);
				int weekTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
				String weekDesc = transNum2Week(weekDays[weekTemp]);
				boolean isToday = false;
				tempMap.put("weekDesc", weekDesc);
				if(j == todayWeek){
					isToday = true;
				}
				tempMap.put("isToday", isToday);
				int month = calendar.get(Calendar.MONTH) + 1;
				int day = calendar.get(Calendar.DAY_OF_MONTH);
				String dateValue = DateTimeUtility.dateofnow(calendar.getTime());
				tempMap.put("dateValue", dateValue);
				tempMap.put("today", month + "/" + day);
				list.add(tempMap);
			}
		}
		return list;
	}
	
	/**
	 * 组装成近7天的日期（今天排首位）
	 * @return
	 */
	public static List<Map<String, Object>> generateWeeksToday(){
		int[] weekDays = {7, 1, 2, 3, 4, 5, 6};
		List<Map<String, Object>> list = new ArrayList<>();
		
		Calendar calendar = Calendar.getInstance();
		for(int i = 0; i < 7; i++){
			Map<String, Object> tempMap = new HashMap<>();
			calendar.setTime(new Date());
			calendar.add(Calendar.DATE, i);
			int weekTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			if(weekTemp < 0){
				weekTemp = 0;
			}
			String weekDesc = transNum2Week(weekDays[weekTemp]);
			boolean isToday = false;
			tempMap.put("weekDesc", weekDesc);
			if(i == 0){
				isToday = true;
			}
			tempMap.put("isToday", isToday);
			int month = calendar.get(Calendar.MONTH) + 1;
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			String dateValue = DateTimeUtility.dateofnow(calendar.getTime());
			tempMap.put("dateValue", dateValue);
			tempMap.put("today", month + "/" + day);
			list.add(tempMap);
		}
		return list;
	}

	/**
	 * 昨天：yyyyMMdd
	 * @return
	 */
	public static String yesterdayDate() {
		return yesterdayDate(0);
	}

	/**
	 * 昨天之前day天：yyyyMMdd
	 * @param day
	 * @return
	 */
	public static String yesterdayDate(int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, 0 - (1 + day));
		String yesterday = new SimpleDateFormat( "yyyyMMdd").format(calendar.getTime());
		return yesterday;
	}

	/**
	 * 获取当前时间的一小时前的小时数
	 * @param date
	 * @return
	 */
	public static String getOneHourAgo(Date date){
		String beforeHour;
		if (date.getHours()== 0){
			beforeHour = "23";
		}else {
			beforeHour = String.valueOf(date.getHours()-1);
		}
		return beforeHour;
	}

	/***
	 * 增加天数
	 *
	 * @param date
	 * @param days
	 * @return
	 */
	public static Date addDays(Date date, int days) {
		if (days == 0) {
			return date;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_YEAR, days);
		return cal.getTime();
	}
	
	public static void main(String[] args) {
        String cutTime = DateTimeUtility.addTimeFormat(null, "F", 80, "HH:mm");
		System.out.println(cutTime);
//		System.out.println(getCurrentMonthDayCount());
	}
}